<template>
  <div>
    <el-dialog title="修改密码" v-model="dialogFormVisible" width="30%" :append-to-body="true">
      <el-form ref="ruleFormRef" :rules="changePasswordFormRules" status-icon label-width="120px"
               :model="passwordModel">
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input v-model="passwordModel.oldPwd" placeholder="请输入旧密码" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="passwordModel.newPwd" placeholder="请输入新密码" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="再来一次" prop="newPwdAgain">
          <el-input v-model="passwordModel.newPwdAgain" placeholder="请再次输入新密码" type="password"
                    show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="ChangePassword(ruleFormRef)">确认</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-form-item label="密码">
      <el-button @click="dialogFormVisible = true">修改密码</el-button>
    </el-form-item>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import {UpdatePassword} from "../../../api/user";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {changePasswordFormRules} from "../../../rules/UserFormRules";

const ruleFormRef = ref({});
const dialogFormVisible = ref(false);
const router = useRouter();
const passwordModel = reactive({
  oldPwd: '',
  newPwd: '',
  newPwdAgain: ''
})

function ChangePassword(formEl) {
  console.log(formEl)
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (passwordModel.newPwd === passwordModel.newPwdAgain) {
        UpdatePassword(passwordModel).then(response => {
          if (response.code === 200) {
            ElMessage({
              message: '修改成功,3秒后跳转到登录页面',
              type: 'success',
              duration: 3 * 1000
            })
            dialogFormVisible.value = false;
            const t = setInterval(() => {
              clearInterval(t);
              router.push('/login');
            }, 3 * 1000);
          } else {
            ElMessage({
              message: response.msg,
              type: 'warning',
              duration: 3 * 1000
            })
          }
        })
      } else {
        ElMessage({
          message: '两次输入的新密码不相同',
          type: 'warning',
          duration: 3 * 1000
        })
      }
    }
  })

}

</script>

<style scoped>

</style>